package com.lglbc.oauth2.config.details.user;

import com.lglbc.oauth2.entity.Role;
import com.lglbc.oauth2.entity.User;
import com.lglbc.oauth2.enums.PasswordEncoderTypeEnum;
import com.lglbc.oauth2.mapper.UserRoleMapper;
import com.lglbc.oauth2.service.RoleService;
import com.lglbc.oauth2.service.UserService;
import com.xiaoleilu.hutool.collection.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class SysUserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userServiceImpl;
    @Autowired
    private RoleService roleServiceImpl;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        Map<String, Object> map = new HashMap<>();
        map.put("username", name);
        User user = userServiceImpl.lambdaQuery().eq(User::getUsername, name).one();
        if (user == null) {
            throw new UsernameNotFoundException("此用户不存在");
        }

        Collection<SimpleGrantedAuthority> grantedAuthorities = new ArrayList<>();
        List<String> roleIds = userRoleMapper.getRoleIdByUserId(user.getId());
        if (CollectionUtil.isNotEmpty(roleIds)){
            List<Role> roles = roleServiceImpl.lambdaQuery().in(Role::getId, roleIds).list();
            List<String> roleCodes = roles.stream().map(Role::getCode).collect(Collectors.toList());
            for (String roleCOde : roleCodes) {
                SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_"+roleCOde);
                grantedAuthorities.add(grantedAuthority);
            }
        }

        return new SysUserDetails(user.getId(), user.getUsername(),PasswordEncoderTypeEnum.BCRYPT.getPrefix() + user.getPassword(),true, grantedAuthorities);
    }


}

